package com.dashan.frontend.client.util;

import java.util.ArrayList;
import java.util.List;

import com.dashan.frontend.client.EventBus;
import com.dashan.frontend.client.event.GeoItemSelectedEvent;
import com.dashan.frontend.client.event.GeoItemSelectedHandler;
import com.google.gwt.maps.client.MapWidget;
import com.google.gwt.maps.client.event.MarkerClickHandler;
import com.google.gwt.maps.client.event.MarkerDoubleClickHandler;
import com.google.gwt.maps.client.geom.LatLng;
import com.google.gwt.maps.client.geom.Point;
import com.google.gwt.maps.client.geom.Size;
import com.google.gwt.maps.client.overlay.Icon;
import com.google.gwt.maps.client.overlay.Marker;

public class GoogleMap implements GeoItemSelectedHandler {
    public static final String ACITVE_ICON = "/resources/rd_hl.png";
    public static final String NORMAL_ICON = "/resources/rd.png";
    public static Icon ICON = Icon.newInstance(NORMAL_ICON);
    static {
        ICON.setIconSize(Size.newInstance(24, 24));
        ICON.setIconAnchor(Point.newInstance(12, 12));
    }
    
    private List<Marker> allMarkers = new ArrayList<Marker>();
    private MapWidget map;
    
    public GoogleMap(MapWidget map) {
        this.map = map;
        LatLng center = LatLng.newInstance(34.307144, 104.062500);
        map.setCenter(center);
        map.setZoomLevel(4);
        map.setScrollWheelZoomEnabled(true);
        
        EventBus.get().addHandler(GeoItemSelectedEvent.TYPE, this);
    }
    
    public void highLightMarker(Marker mk) {
        for (Marker m : allMarkers) {
            m.setImage(NORMAL_ICON);
        }
        mk.setImage(ACITVE_ICON);
    }
    
    public void addMarker(final Marker m) {
        m.addMarkerClickHandler(new MarkerClickHandler() {
            @Override
            public void onClick(MarkerClickEvent event) {
                EventBus.get().fireEvent(new GeoItemSelectedEvent(m));
            }
        });
        m.addMarkerDoubleClickHandler(new MarkerDoubleClickHandler() {
            @Override
            public void onDoubleClick(MarkerDoubleClickEvent event) {
                EventBus.get().fireEvent(new GeoItemSelectedEvent(m, true));
            }
        });
        
        allMarkers.add(m);
        map.addOverlay(m);
    }
    
    public void removeMarker(Marker m) {
        allMarkers.remove(m);
        map.removeOverlay(m);
    }
    
    public void clearMarker() {
        allMarkers.clear();
        map.clearOverlays();
    }
    
    public MapWidget getMap() {
        return map;
    }
    
    @Override
    public void onGeoItemSelected(GeoItemSelectedEvent event) {
        if (event.getGeoRecord().getMarker() != null) {
            highLightMarker(event.getGeoRecord().getMarker());
            if (event.isMoveToCenter()) {
                map.panTo(event.getGeoRecord().getMarker().getLatLng());
            }
        }
    }
}
